package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.intercepror.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 添加联系人
     */
    public void contacts(Long userId) {
        Long currUserId = UserHolder.getUserId();
        //1、把好友数据存入到MongoDB
        friendApi.save(currUserId,userId);
        //2、将好友关系，写入到环信
        huanXinTemplate.addContact("hx"+currUserId,"hx"+userId);//添加好友的环信用户名
    }

    //查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、根据用户id，分页查询列表（List<Friend）
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        //3、判断好友列表是否存在
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取所有的好友id
        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);
        //获取所有的好友信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //4、循环List<Friend>，一个Friend构建一个ContactVo
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //获取好友id
            Long friendId = friend.getFriendId();
            //查询好友信息
            UserInfo userInfo = map.get(friendId);
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        //5、返回
        return new PageResult(page,pagesize,0l,vos);
    }

    //根据环信用户，查询用户信息  hx6   -- 6
    public UserInfoVo findByHuanxin(String huanxinId) {
        String temp = huanxinId.substring(2);
        Long userId = Long.valueOf(temp);
        UserInfo userInfo = userInfoApi.findById(userId);
        //转化vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //同名同类型
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }
}
